<!-- 新增编辑部门 -->
<template>
  <div>
    <el-dialog
      :title="isAdd == 1 ? '新增部门' : '修改部门'"
      :visible.sync="addEditVisible"
    >
      <el-form
        class="formView"
        ref="form"
        :model="formdata"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="部门名称:" prop="deptName">
          <el-input
            v-model="formdata.deptName"
            clearable
            placeholder="部门名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="部门编码:" prop="deptCode">
          <el-input
            v-model="formdata.deptCode"
            :disabled="isAdd == 2"
            placeholder="部门编码"
          ></el-input>
        </el-form-item>

        <el-form-item label="上级部门" prop="parentIds">
          <el-cascader
            :props="propss"
            :options="deptList"
            v-model="formdata.parentIds"
            clearable
          >
          </el-cascader>
        </el-form-item>

        <!-- <el-form-item label="排序:" prop="sort">
          <el-input
            v-model="formdata.sort"
            clearable
            placeholder="排序"
          ></el-input>
        </el-form-item> -->

        <el-form-item label="部门全称:" prop="fullName">
          <el-input
            v-model="formdata.fullName"
            placeholder="部门全称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictList } from '@/api/pubilcClass'
import {
  addDept,
  updateDept,
  removeDept,
  getDeptDetails
} from '@/api/rightsManage'
export default {
  components: {},
  props: {
    isAdd: {
      type: Number,
      default() {
        return 1
      }
    },
    detailData: {
      type: Object,
      default() {
        return {}
      }
    },
    deptList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      addEditVisible: false,
      formdata: {
        deptCode: '',
        deptName: '',
        parentId: '',
        fullName: '',
        sort: '',
        state: '',
        parentIds: []
      },
      channelPlatformList: [],
      channelTypeList: [],
      rules: {
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        deptCode: [
          { required: true, message: '请输入部门编码', trigger: 'blur' }
        ],
        parentIds: [
          {
            type: 'array',
            required: true,
            message: '请选择上级部门',
            trigger: 'change'
          }
        ]
      },
      propss: {
        lazy: false,
        value: 'deptId',
        label: 'deptName',
        children: 'childrens',
        expandTrigger: 'hover',
        checkStrictly: true
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.onSubmit()
        } else {
          return false
        }
      })
    },
    onSubmit() {
      console.log(this.formdata)
      if (this.isAdd == 1) {
        addDept(this.formdata).then(res => {
          this.$message({
            message: this.isAdd == 1 ? '新增成功' : '修改成功',
            type: 'success'
          })
          this.$parent.getDataList()
          this.resetForm('form')
        })
      } else if (this.isAdd == 2) {
        if (this.formdata.parentId == this.formdata.deptId) {
          this.$message({
            message: '当前部门不能作为自己的子部门！',
            type: 'error'
          })
          return false
        }
        updateDept(this.formdata).then(res => {
          this.$message({
            message: this.isAdd == 1 ? '新增成功' : '修改成功',
            type: 'success'
          })
          this.$parent.getDataList()
          this.resetForm('form')
        })
      }
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields()
      this.formdata = {
        deptCode: '',
        deptName: '',
        parentId: '',
        fullName: '',
        sort: '',
        state: '',
        parentIds: []
      }
      this.addEditVisible = false
    },
    // 树转线性结构
    hasChildrenId(root) {
      const list = []
      if (root) {
        const Root = JSON.parse(JSON.stringify(root))
        const queue = []
        queue.push(Root)
        while (queue.length) {
          const node = queue.shift()
          if (node.childrens && node.childrens.length) {
            queue.push(...node.childrens)
          }
          delete node.childrens
          if (node.parentId !== null && node.parentId !== undefined) {
            list.push(node)
          }
        }
      }
      return list
    },
    // 获取部门 parentIds
    getChildrenIds(deptId) {
      let Root = JSON.parse(
        JSON.stringify(this.hasChildrenId(this.deptList[0]))
      )
      console.log(Root)
      let list = []
      let findParentId = (root, deptId) => {
        root.forEach((current, index) => {
          if (current.deptId == deptId && current.parentId > 0) {
            list.push(current.parentId)
            let temp = JSON.parse(
              JSON.stringify(
                root.slice(0, index).concat(root.slice(index + 1, root.length))
              )
            )
            findParentId(temp, current.parentId)
          }
        })
      }
      findParentId(Root, deptId)
      list.reverse()
      return list
    }
  },
  watch: {
    addEditVisible: {
      deep: true,
      handler(now, old) {
        if (now) {
          if (this.isAdd == 2) {
            this.formdata = Object.assign({}, this.formdata, this.detailData)
            this.formdata.parentIds = this.getChildrenIds(
              this.detailData.deptId
            )
          }
        } else {
          this.resetForm('form')
        }
      }
    },
    'formdata.parentIds': {
      deep: true,
      handler(now, old) {
        if (now) {
          this.formdata.parentId = now[now.length - 1]
        } else {
          this.formdata.parentId = ''
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog {
    width: 500px;
    border-radius: 10px;
  }
  .el-dialog__title {
    font-size: 16px;
  }
  .el-input {
    width: 250px;
  }
  .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0px;
  }
  .el-form {
    padding: 10px 0;
  }
  .el-input__inner {
    height: 35px;
    line-height: 35px;
  }
  .el-form-item {
    margin-bottom: 15px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-dialog__footer {
    padding-top: 10px;
    padding-bottom: 10px;
    border-top: 1px solid #eee;
  }
}
.formView {
  border-top: 1px solid #eee;
  .sortInput {
    width: 100px;
  }
}
</style>
